import { defineStore } from 'pinia';
import { getNewAppVersionApi } from '@/api/app';
import { previewFile } from '../api/uploadConfig';

export const useAppStore = defineStore('app', {
  state: () => ({
    version: '1.2.0',
    newVersion:'',
    isOpenAppUpdate: false,
  }),
  actions: {
    checkAppUpdate(){
      if(!this.newVersion || this.newVersion != this.version){
        this.getNewAppVersion()
      }
    },
    getNewAppVersion() {
      return getNewAppVersionApi()
        .then(res => {
          const resData = res.data;
          const {version:newVersion,url} = resData;
          this.newVersion = newVersion;

          if(newVersion && newVersion != this.version){
            const fileDownloadUrl = `${previewFile}/${url}`;

            if(!this.isOpenAppUpdate){
               uni.showModal({
                title: '版本更新',
                content: 'app有新版本，请立即更新，以免影响您的使用',
                showCancel: false,
                confirmText: '立即更新',
                success: () => {
                  this.isOpenAppUpdate = false
                  plus.runtime.openURL(fileDownloadUrl);
                }
              });

              this.isOpenAppUpdate = true
            }

            return Promise.reject()
          }

          return Promise.resolve();
        })
        .catch(Promise.reject);
    },
  }
});
